﻿/**
 * Created by zlkmu on 2017/5/17.
 */

//用于保存选择的用户的数组
var selectUser = [];

//辅助函数，用于查询是否添加过当前用户
function isSelectUser(departText, departVal, userText, userVal){
    if(selectUser.length != 0) {
        for (var i = 0; i < selectUser.length; i++) {
            if (selectUser[i]['userVal'] == userVal)
                return {'state': true, 'index': i};
        }
    }
    selectUser.push({'departText': departText, 'departVal': departVal, 'userText': userText, 'userVal': userVal});
    return {'state': false, 'index': -1};
}
//辅助函数，用于删除添加过的用户
function deleteCurUser(departText, userText){
    var curIndex = -1;
    if(selectUser.length != 0){
        for(var i = 0; i < selectUser.length; i++){
            if (selectUser[i]['departText'] == departText && selectUser[i]['userText'] == userText){
                curIndex = i;
                break;
            }
        }
        if(curIndex != -1){
            selectUser.splice(curIndex, 1);
        }
    }
}
//辅助函数，设置默认用户（即用户本身)
function setDefaultUser(){
    //获取当前用户
    var curUserInfo = JSON.parse(window.localStorage.getItem('user_info'));
    //获取当前部门
    var curDepartmentID = window.localStorage.getItem('cur_department');
    selectUser.push({'departText': curUserInfo.department_info[curDepartmentID].department_name,
        'departVal': curUserInfo.department_info[curDepartmentID].department_id,
        'userText': curUserInfo.user_name,
        'userVal': curUserInfo.user_id});

    var id = selectUser.length - 1;
    $('#people_table').append("<tr class='tr user_tr'> " +
        "<td class='td_center'><input type='checkbox'></td> " +
        "<td class='td_center'>" + (id + 1) +  "</td> " +
        "<td class='td_center'>" + selectUser[id]['userText'] + "</td>" +
        "<td class='td_center'>" + selectUser[id]['departText'] + "</td>" +
        "<td class='td_center'></td> " +
        "</tr>");

}

//辅助函数，处理删除某条记录
function deleteUserItem(elem){
    //如果按下删除键
    //获取删除键前面的tr
    var curElem = $(elem).parent().parent();
    //获取tr下的用户和部门信息
    var userText = $(curElem).children('td').eq(2).text();
    var departText = $(curElem).children('td').eq(3).text();
    //移除原始数组中对应的信息
    deleteCurUser(departText, userText);
    //移除tr
    $(elem).parent().parent().remove();
    //重新对剩下的tr编号
    $('.user_tr').each(function(index){
        $(this).children('td').eq(1).text(index+1);
    })
}

//辅助函数，当添加用户按钮按下的时候
function AddUser(){
    //设置默认用户
    //setDefaultUser();
    //如果按下添加按钮
    $('#add_people_button').click(function(){
        //获取选择框中对应的用户和部门信息
        var checkDepartText = $('#depart-select').find("option:selected").text();
        var checkUserText = $('#user-select').find("option:selected").text();

        var checkDepartVal = $("#depart-select").val();
        var checkUserVal = $('#user-select').val();
        //查询是否已经添加
        if(isSelectUser(checkDepartText, checkDepartVal, checkUserText, checkUserVal).state){
            $.prompt( "<h5>已经添加该用户</h5>",{
                title: '错误提醒',
                buttons: {'确定': true}
            });
            return;
        }
        //获取最新的index，即人数数量
        var curIndex = selectUser.length - 1;

        $('#people_table').append("<tr class='tr user_tr'> " +
            "<td class='td_center'><input type='checkbox'></td> " +
            "<td class='td_center'>" + (curIndex + 1) +  "</td> " +
            "<td class='td_center'>" + selectUser[curIndex]['userText'] + "</td>" +
            "<td class='td_center'>" + selectUser[curIndex]['departText'] + "</td>" +
            "<td class='td_center'><a href='' class='ext_btn del_btn'><span class='del'></span>删除</a></td> " +
            "</tr>");

        $('.del_btn').eq(selectUser.length-2).on('click', function(e){
                        deleteUserItem(this);
                        //防止默认按钮的操作
                        e.preventDefault();
        })
    })
}
//辅助函数，处理出差类别
function getBusinessType(){
    if($('#business_type option').length == 0){
        //ajax获取出差类别信息
        $.get(url+'Common/GetBusiness_type.php', function(data){
            var t = JSON.parse(data);
            for(var i = 0; i < t['data'].length; i++){
                $('#business_type').append("<option value='"+ t['data'][i]['type_id'] + "'>" + t['data'][i]['type_name'] + "</option>");
            }
        })
    }
}

//辅助函数，处理大案要案获取
function getCaseInfo(){
    $.get(url+'Common/GetMajorCase.php', function(data){
        var t = JSON.parse(data);
        for(var i = 0; i < t['data'].length; i++){
            $('#case_info').append("<option value="+ t['data'][i]['case_id'] + ">" + t['data'][i]['case_name'] + "</option>");
        }
    })
}
//辅助函数,处理出差类别选择和大案要案获取
function processBusinessTypeChange() {
    $('#business_type').change(function(){
        //大案要案类别为2
        if($(this).val() == 2){
            $('#case_wrap').css('display', '');
            if($('#case_info option').length == 0){
                //ajax获取大案要案信息
                getCaseInfo();
            }
        }else{
            $('#case_wrap').css('display', 'none');
        }
    });
}

//辅助函数，处理时间选择
function processTime(){
    var startDateTextBox = $('#business_start_time');
    var endDateTextBox = $('#business_end_time');
    startDateTextBox.datetimepicker({
        onClose: function(dateText, inst) {
            if (endDateTextBox.val() != '') {
                var testStartDate = startDateTextBox.datetimepicker('getDate');
                var testEndDate = endDateTextBox.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    endDateTextBox.datetimepicker('setDate', testStartDate);
            }
            else {
                endDateTextBox.val(dateText);
            }
        },
        onSelect: function (selectedDateTime){
            endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate') );
        }
    });
    endDateTextBox.datetimepicker({
        onClose: function(dateText, inst) {
            if (startDateTextBox.val() != '') {
                var testStartDate = startDateTextBox.datetimepicker('getDate');
                var testEndDate = endDateTextBox.datetimepicker('getDate');
                if (testStartDate > testEndDate)
                    startDateTextBox.datetimepicker('setDate', testEndDate);
            }
            else {
                startDateTextBox.val(dateText);
            }
        },
        onSelect: function (selectedDateTime){
            startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate') );
        }
    });
}

//辅助函数，计算天数
function calcDays(){
    $('#business_end_time').on('change', function(){
        var b = new Date($('#business_start_time').val());
        var e = new Date($('#business_end_time').val());
        var d = Math.round((e - b) / 1000 / 60 / 60 / 24);
        $('#days').val(d);
    })
    $("#business_start_time").change(function(){
        var b = new Date($('#business_start_time').val());
        var e = new Date($('#business_end_time').val());
        if(e == 'Invalid Date'){
            return;
        }
        var d = Math.round((e - b) / 1000 / 60 / 60 / 24);
        $('#days').val(d);
    })


}

//辅助函数，处理上传文件
function processUploadFile(){
    $('#upload_file_area').attr('action', url+'UploadFile.php');
    $('#uploadButton').click(function(){
        if($(this).hasClass('disabled')){
            return;
        }
        $('#upload').click();
    });
    $('#upload').change(function(){
        var fileStr= $(this).val();
        if(fileStr == ''){
            $('#filearea').val('');
            return;
        }
        var files = fileStr.split(',');
        if(files.length > 3){
            $.prompt( "<h5>请最多上传三个文件</h5>",{
                title: '错误提醒',
                buttons: {'确定': true}
            });
            return;
        }
        var tempStr = '';
        var isOk = true;
        for(var i = 0; i < files.length; i++){
            var filename = files[i].substring(files[i].lastIndexOf('\\') + 1);
            var fileExt = files[i].substring(files[i].lastIndexOf('.') + 1);
            fileExt = fileExt.toLowerCase();
            if(fileExt == 'doc' || fileExt == 'docx' || fileExt == 'pdf' || fileExt == 'xls' || fileExt == 'xlsx'
                || fileExt == 'txt' || fileExt == 'ppt' || fileExt == 'pptx' || fileExt == 'jpg' || fileExt == 'png' || fileExt == 'jpeg') {
                tempStr += filename + ";";
            }
            else{
                $.prompt( "<h5>仅支持WORD/EXCEL/PPT/PDF/TXT/JPG/JPEG/PNG格式文件上传</h5>",{
                    title: '错误提醒',
                    buttons: {'确定': true}
                });
                isOk = false;
                break;
            }
        }
        if(isOk){
            $('#filearea').val(tempStr);
        }
    })


    $('#clearFile').click(function(){
        $('#filearea').val('');
        $('#upload_file_area').reset();
        $('#clearFile').css('display', 'none');

    })
}

//辅助函数，处理借车按钮
function processLoanCarBtn(){
    //处理借车选择
    $("input[name='isLoanCar']").click(function(){
        var v = $(this).val();
        if(v == 1){
            $('#loanCar').show();
        }
        else{
            $('#loanCar').hide();
            loanCarData = {};
            isSetCarData = false;
        }
    })
}

//辅助函数，处理借款按钮
function processLoanMoneyBtn(){
    //处理借款选择
    $("input[name='isLoanMoney']").click(function(){
        var v = $(this).val();
        if(v == 1){
            $('#loanMoney').show();
        }
        else{
            $('#loanMoney').hide();
            loanMoneyData = {};
            isSetMoneyData = false;
        }
    })
}

//辅助函数，处理借车信息
function processLoanCarData(){
    var reason = $('#loanCar_reason').val();
    if(reason == ""){
        return false;
    }
    loanCarData.reason = reason;
    loanCarData.carNum = $('#loanCar_num').val();
    loanCarData.proDriver = $("input[name='proDriver']:checked").val();
    if(loanCarData.proDriver){
        loanCarData.driverName = $('#loanCar_driver_info').val();
    }
    else{
        loanCarData.driverID = "";
        loanCarData.driverName = "";
    }
    return true;
}

//辅助函数，清空驾驶员信息
function clearDriver(){
    if($('#clear_driver_btn').hasClass('disabled')){
        return ;
    }

    $('#clear_driver_btn').click(function(){
        loanCarData.driverID = "";
        $('#loanCar_driver_info').val('');
    })
}

//辅助函数，处理添加司机的信息
function addDriver(){
    if($('#add_driver_btn').hasClass('disabled')){
        return;
    }
    $('#add_driver_btn').click(function(){
        var t = $('#loanCar_driver_info').val();
        var temp = $('#loanCar_driver').find('option:selected').text();

        var tempDrivers = t.split(";");
        var e = false;
        for(var i = 0; i < tempDrivers.length; i++){
            if(temp == tempDrivers[i]){
                e = true;
                break;
            }
        }
        if(e){
            $.prompt("<h3>已经添加该司机</h3>", {
                title: '错误提醒',
                buttons: {'确定': true}
            })
        }
        else{
            t += temp + ";";
            $('#loanCar_driver_info').val(t);
            loanCarData.driverID += $('#loanCar_driver').val() + ";";

        }

    })
}

//辅助函数，处理借款信息
function processLoanMoneyData(){
    var reason = $('#loanMoney_reason').val();
    var money = $('#loanMoney_amount').val();
    loanMoneyData.reason = reason;
    loanMoneyData.money = money;
}

//辅助函数，获取部门
function getSection(){
    $('#depart-select').empty();
    $('#dataLoad').show();
    $.get(url + 'Common/GetSection.php', function(result){
        $('#dataLoad').hide();
        var t = JSON.parse(result);

        for(var i = 0; i < t.length; i++){
            var id = t[i]['section_id'];
            var name = t[i]['section_name'];
            $('#depart-select').append("<option value='"+id+"'>" + name + "</option>");
        }
        $('#depart-select').comboSelect();

        $('#depart-select').trigger('change');
    })
}
//辅助函数，获取部门成员
function getSectionMember(){
    $('#depart-select').change(function(){
        $('#user-select').empty();
        var checkValue = $(this).val();

        //var checkText = $(this).find("option:selected").text();
        $.post(url + 'Common/GetSectionUser.php', {'sectionID': checkValue}, function(data){

            var t = JSON.parse(data);

            if(t['state'] == 1){
                for(var i = 0 ; i < t['data'].length; i++){
                    $("#user-select").append("<option value='"+t['data'][i]['user_id']+"'>" + t['data'][i]['user_name'] + "</option>");
                }
                $('#user-select').comboSelect();
            }
            else{
                $.prompt( "<h5>该部门没有成员</h5>",{
                    title: '错误提醒',
                    buttons: {'确定': true}
                });
            }
        })

    })
}

//辅助函数，处理上传文件
function uploadFile(data, type){
    var formData = new FormData($('#upload_file_area')[0]);
    formData.append('type', type);
    formData.append('id', data.approval_id);
    $.ajax({
        type: 'POST',
        data: formData,
        url: url + 'UploadFile.php',
        contentType: false,
        processData: false,
        async:false,
        success: function(data){
            var t = JSON.parse(data);
            $('#dataLoad').hide();
            if(t.state == 1){
                $.prompt( "<h3>提交成功，请耐心等待审批</h3>",{
                    title: '消息提醒',
                    buttons: {'确定': true},
                    submit: function(e, v, m, f){
                        if(v){
                            if(type == 1){
                                jumpPage('my_bussiness_approval.html');
                            }
                            else{
                                jumpPage('my_fee_apply.html');
                            }
                        }
                    }
                });
            }
            else{
                $.prompt( "<h5>网络错误，请联系管理员</h5>",{
                    title: '错误提醒',
                    buttons: {'确定': true}
                });
                $('#dataLoad').hide();
            }

        },
        error: function(data){
            $.prompt( "<h5>网络错误，请联系管理员</h5>",{
                title: '错误提醒',
                buttons: {'确定': true}
            });
            $('#dataLoad').hide();
        }
    });
}

//辅助函数，生成上传数据
function createPostData(){
    var postData = {};
    if(isModifyMode){
        postData.prev_app_id =curItem.approval_ID;
    }
    else{
        postData.prev_app_id = '';
    }
    postData.user = selectUser;
    postData.business_type = $('#business_type').val();
    postData.major_case = (postData.business_type == 2 ? $('#case_info').val() : '');
    var destination = $('#city-picker3').val();
    if(destination == ''){
        $.prompt( "<h3>未填写出差地，请填写出差地后再提交</h3>",{
            title: '错误提醒',
            buttons: {'确定': true}
        });
        return false;
    }
    var destArray = destination.split('/');
    postData.destination = {
        'province': destArray[0],
        'city': destArray[1],
        'county': destArray[2],
        'detail-county': $('#county').val()
    };
    postData.startTime = $('#business_start_time').val();
    postData.endTime = $('#business_end_time').val();
    if(postData.startTime == '' || postData.endTime == ''){
        $.prompt( "<h3>未填写或未选择正确的出差时段，请重新填写后提交</h3>",{
            title: '错误提醒',
            buttons: {'确定': true}
        });
        return false;
    }
    postData.reason = $('#business_reason').val();
    if(postData.reason == ''){
        $.prompt( "<h3>未填写出差理由，请重新填写后提交</h3>",{
            title: '错误提醒',
            buttons: {'确定': true}
        });
        return false;
    }
    postData.driveSelf = $('input:radio[name="driveSelf"]:checked').val();
    return postData;
}

//辅助函数，上传数据
function uploadData(postData){
    $('#dataLoad').show();
 //   console.log(JSON.stringify(postData));
    $.post(url + '/BusinessApprove/CreateBusinessApprove.php', postData, function(data){

        var files = $('#upload').val();
        var t = JSON.parse(data);

        $('#dataLoad').hide();
        if(t.state == 1){
            if(files == ''){
                $.prompt( "<h3>提交成功，请耐心等待审批</h3>",{
                    title: '消息提醒',
                    buttons: {'确定': true},
                    submit: function(e, v, m, f){
                        if(v)
                            jumpPage('my_bussiness_approval.html');
                    }
                });
            }
            else{
                uploadFile(t, 1);
            }
        }
        else{
            $.prompt( "<h3>网络或数据库错误，请稍后再试</h3>",{
                title: '错误提醒',
                buttons: {'确定': true}
            });
        }
    })
}

//辅助函数，清空所有数据
function clearData(){
    //清空Table
    $('.user_tr').remove();
    selectUser=[];

    //恢复用户表
    setDefaultUser();

    $('#business_type').val(1).change();
    $('#city-picker3').val('').change();
    $('#county').val('');
    $('#business_reason').val('').change();
    $('#upload').val('').change();
    $('#business_start_time').val('').change();
    $('#business_end_time').val('').change();
    $('#days').val(0);
}

//辅助函数，获取司机
function getDriver(){
    if($('#loanCar_driver option').length > 0){
        return;
    }
    $.get(url+'Common/GetDriverInfo.php', function(data){
        var t = JSON.parse(data);
        if(t.state == 1){
            $('#loanCar_driver').empty();
            for(var i = 0; i < t.drivers.length; i++){
                $('#loanCar_driver').append("<option value='" + t.drivers[i]['user_ID'] + "'>" + t.drivers[i]['user_name'] + "</option>");
            }
        }
        else{
            $.prompt("<h3>网络或数据库错误，无法获得驾驶员信息</h3>", {
                title: '错误提醒',
                buttons: {'确定': true}
            })
        }
    })
}


